package com.hefan.monitor.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.service.JedisService;
import com.cat.tiger.util.CollectionUtils;
import com.hefan.live.itf.LiveMonitorService;
import com.hefan.monitor.bean.LiveSnapshot;
import com.hefan.monitor.configCenter.MonitorConfigCenter;
import com.hefan.monitor.dao.LiveSnapshotDao;
import com.hefan.monitor.green.CheckYellowService;
import com.hefan.monitor.itf.LiveYellowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.xml.bind.SchemaOutputResolver;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

@Component("liveYellowService")
public class LiveYellowServiceImpl implements LiveYellowService {
	
	private Logger logger = LoggerFactory.getLogger(LiveYellowServiceImpl.class);
	
	@Resource
	JedisService jedisService;
	@Resource
	CheckYellowService checkYellowService;
	@Resource
	LiveSnapshotDao liveSnapshotDao;
	@Reference
	LiveMonitorService liveMonitorService;
	@Resource
	private MonitorConfigCenter monitorConfigCenter;
	
	//private final String START = PayPropertiesUtils.getString("monitor.one");
	private final String END = ".jpg";
	private static int qn =1;

	@SuppressWarnings("finally")
	@Override
	public ResultBean uploadLiveSnapshot() {
		// TODO Auto-generated method stub
		ResultBean resBean = new ResultBean(ResultCode.SUCCESS);
		Map<String, String> config = monitorConfigCenter.getPublicConfig();
		String START=config.get("monitor.one");
		if(qn>=3){
			//调用外部查询直播间加入缓存
			liveMonitorService.getCurrentlyOnLiveList();
			qn =1;
		}else{
			qn++;
		}
		try {
			Set s = jedisService.keys("jh_*");
			Iterator it = s.iterator();
			while (it.hasNext()) {
				List<String> list = new ArrayList<String>();
				String key = (String) it.next();
				String value = jedisService.getStr(key);
				Map resultMap = JSON.parseObject(value, Map.class);
				int imgNo = Integer.parseInt(resultMap.get("imgNo").toString());
				int no = imgNo;
				int imgErrNum = Integer.parseInt(resultMap.get("imgErrNum").toString());
				for(int i=imgNo;i<imgNo+50;i++){
					String url =START + key.replace("jh_","") + "/" + i + END;
					if(!this.checkImgHas(url)){
						Map<String,Object> map = new HashMap<String,Object>();
						map.put("imgNo", i);
						if(imgNo == i){
							map.put("imgErrNum", imgErrNum+1);
						}else{
							map.put("imgErrNum", 0);
						}
						jedisService.setexStr(key, JSON.toJSONString(map), 60*60);
						if(imgErrNum>=3){
							//超过3次没取到-移除此直播间缓存
							jedisService.del(key);
						}
						break;
					}
					list.add(url);
				}
				if(CollectionUtils.isEmptyList(list)){
					continue;
				}
				//处理
				List<Map<String,String>> resList = checkYellowService.AsyncImageDetectionSample(list);
				if(CollectionUtils.isEmptyList(resList)){
					continue;
				}
				for(int j=0;j<resList.size();j++){
					Map<String,String> resMap = resList.get(j);
					//处理快照
					int r = this.dealLiveSnapshot(resMap);
					if(r>0 && r>=no){
						no = r+1;
					}
				}
				//更新缓存
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("imgNo", no);
				map.put("imgErrNum", 0);
				jedisService.setexStr(key, JSON.toJSONString(map), 60*60);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("处理图片异常："+e.getMessage());
		}finally {
			return resBean;
		}
		
	}

	@SuppressWarnings("finally")
	@Override
	public ResultBean dealLiveSnapshot() {
		// TODO Auto-generated method stub
		ResultBean resBean = new ResultBean(ResultCode.SUCCESS);
		try {
			List<LiveSnapshot> list = this.liveSnapshotDao.getLiveSnapshotList();
			if(!CollectionUtils.isEmptyList(list)){
				List<String> taskList = new ArrayList<String>();
				for(int i=0;i<list.size();i++){
					LiveSnapshot liveSn = list.get(i);
					taskList.add(liveSn.getTaskId());
				}
				List<Map<String,String>> resList = this.checkYellowService.AsyncImageDetectionResultSample(taskList);
				if(!CollectionUtils.isEmptyList(resList)){
					//修改数据库
					for(int j=0;j<resList.size();j++){
						Map<String,String> resMap = resList.get(j);
						String taskId = resMap.get("taskId");
						String label = resMap.get("label");
						String rate = resMap.get("rate");
						try {
							//处理快照
							this.liveSnapshotDao.updateLiveSnapshotByTaskId(label, rate, taskId);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							logger.error("修改快照返回失败：图片地址:"+taskId);
							logger.error("修改快照返回失败：错误信息："+e.getMessage());
							continue;
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.info("处理图片返回异常："+e.getMessage());
		}finally {
			return resBean;
		}
	}

	@Override
	public ResultBean delKamPictures(int days,int rate) {
		ResultBean resBean = new ResultBean(ResultCode.SUCCESS);
		try {
			this.liveSnapshotDao.delKamPictures(days,rate);
		} catch (Exception e) {
			logger.error("删除鉴黄图片定时任务失败："+e);
		}
		return resBean;
	}

	/**
	 * 判断图片是否存在
	 * @Title: checkImgHas   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param imgUrl
	 * @return      
	 * @return: boolean
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年11月11日 上午10:44:45
	 */
	private boolean checkImgHas(String imgUrl){
    	try {
            URL url = new URL(imgUrl);
            // 返回一个 URLConnection 对象，它表示到 URL 所引用的远程对象的连接。
            URLConnection uc = url.openConnection();
            // 打开的连接读取的输入流。
            InputStream in = uc.getInputStream();
            return true;
        } catch (Exception e) {
           return false;
        }
	}
	
	/**
	 * 处理快照
	 * @Title: dealLiveSnapshot   
	 * @Description: TODO(这里用一句话描述这个方法的作用)   
	 * @param map      
	 * @return: int
	 * @author: LiTeng      
	 * @throws 
	 * @date:   2016年11月11日 下午3:11:05
	 */
	private int dealLiveSnapshot(Map<String,String> resMap){
		LiveSnapshot liveSnapshot = new LiveSnapshot();
		String imageName = resMap.get("imageName");
		try {
			String purl = imageName.substring(0, imageName.lastIndexOf("/"));
			String userId = purl.substring(purl.lastIndexOf("/")+1).split("hefan")[0];
			String liveUuid = purl.substring(purl.lastIndexOf("/")+1);
			String picUrl = imageName.substring(0, imageName.lastIndexOf("."));
			int picNum = Integer.parseInt(picUrl.substring(picUrl.lastIndexOf("/")+1));
			liveSnapshot.setUserId(userId);
			liveSnapshot.setLiveUuid(liveUuid);
			liveSnapshot.setImgNo(picNum);
			liveSnapshot.setImgUrl(imageName);
			liveSnapshot.setTaskId(resMap.get("taskId"));
			liveSnapshot.setLabel(0);
			liveSnapshot.setRate("0");
			liveSnapshot.setStatus(0);
			liveSnapshot.setDeleteFlag(0);
			liveSnapshot.setCreateTime(new Date());
			liveSnapshot.setUpdateTime(new Date());
			//保存数据库
			this.liveSnapshotDao.save(liveSnapshot);
			return picNum;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("保存快照失败：图片地址:"+imageName);
			logger.error("保存快照失败：错误信息："+e.getMessage());
			return 0;
		}
	}

	public static void main(String[] args) {
		LiveYellowServiceImpl service = new LiveYellowServiceImpl();
		System.out.println(service.checkImgHas("http://live-pic1.oss-cn-hangzhou.aliyuncs.com/live1/1101442hefan20161222020615/188.jpg"));
	}
}
